import {FormApi} from "@/api/modules/form/formApi";
import Util from "@/js/Util.js"
import FormConstant from "../../../../../js/FormConstant";

/**
 * 自定义查询
 * @type {{}}
 */
let CustomQuery = {};

/**
 * <pre>
 * 执行自定义查询
 * </pre>
 *  @param {Object} config  -自定义查询配置
 * @param {Object} row  -子表数据
 * @param {String} tableName -子表名
 * @param {Object} formData  -表单数据
 * @returns
 */
CustomQuery.executeCustomQuery=function (config,row,tableName,formData,formVm){
    //未配置自定义查询则跳过
    if(!config.customQuery){
        return;
    }
    //自定义查询key
    let key=JSON.parse(config.customQuery).value;
    //tableType 当前字段是主表还是子表
    let tableType = "";
    if(tableName=="main"){
        tableType="main";
    }else {
        let subData = formData[FormConstant.SubPrefix+tableName];
        tableType=subData instanceof Array?"subTable":"oneTable";
    }
    //查询参数数组
    let gridInput = config.gridInput;
    //构建查询参数
    let params = CustomQuery.getParamsInput(gridInput,formData, row,formVm);
    let paramsStr = JSON.stringify(params);
    //无查询条件跳过
    if (paramsStr == '{}') {
        return;
    }
    FormApi.queryForJson(key,{params: JSON.stringify(params)}).then(res=>{
        if(!res || !res.data){
            return;
        }
        let rows = res.data;
        if (!(rows instanceof Array)) rows = [rows];
        if (rows.length == 0) {
            return;
        }
        //执行回调 rows 返回的数据,row 子表数据
        if(config.callBack && formVm[config.callBack]){
            formVm[config.callBack](rows,row);
        }

        CustomQuery.bindData(config,rows, tableType,row,formData,formVm);
    });
}

/**
 * <pre>
 * 构建查询参数.
 * </pre>
 * @param {Array} gridInput -条件参数配置
 * @param {Object} data  -表数据
 * @param {Object} row  -子表数据
 * @returns
 */
CustomQuery.getParamsInput=function (gridInput, data, row,formVm) {
    if (!gridInput || gridInput.length == 0) return {};
    let param = {};
    for (let i = 0, j = gridInput.length; i < j; i++) {
        let obj = gridInput[i];
        let bindVal = obj.bindVal;
        let valMode = obj.valMode;
        let table = obj.table;
        let mode = obj.mappingMode;
        let val = "";
        //映射方式
        if (mode == "mapping") {
            val = "main" == table || "curForm" == table ? data[bindVal] : row[bindVal]
        } else if (mode == "fixed"){
            val = bindVal;
        }else {
            //脚本方式
            let mainTable = true;
            if (table != "main") {
                mainTable = false;
            }
            
            if(formVm[bindVal]){
                val = formVm[bindVal](data, row, mainTable);
            }else {
                /*
                *参数：
                * data:表单数据
                * row: 行数据
                * mainTable：是否主表
                 */
                let func = new Function("data", "row", "mainTable", bindVal);
                val = func(data, row, mainTable);
            }
        }
        let paramVal = "";
        if(val){
            if (mode == "mapping") {
                if (valMode == "single" && obj.ctlType!="buttonEditSingle") {
                    paramVal = val;
                } else {
                    let json = JSON.parse(val)
                    paramVal = json.value;
                }
            } else {
                paramVal = val;
            }
        }
        if (!paramVal) { //父联动字段为空
            delete param[obj.field];
        }else {
            param[obj.field] = paramVal;
        }
    }
    return param;
}

/**
 * <pre>
 * 将自定义查询获取的数据根据配置放入表单中
 * </pre>
 * @param {Object} config -自定义查询配置
 * @param {Object} data -获取的数据
 * @param {String} tableType -当前所在表类型 main subTable oneTable
 * @param {Object} row -当前表数据
 * @param {Object} formData -表单数据
 */
CustomQuery.bindData=function (config,data,tableType,row,formData){
    //绑定字段数组
    let gridReturn = config.gridReturn;
    //绑定字段是主表还是子表
    let gridName = config.gridName;
    if(!gridName){
        return;
    }
    //存放主表或一对一子表临时数据
    let tmpObj = {};
    //存放一对多子表临时数据
    let subAry = [];
    for (let i = 0; i < data.length; i++) {
        //子表对象
        let isSubData=false;
        let subObj = {
            index_: Util.randomId(),
            selected: false
        }
        for (let j = 0; j < gridReturn.length; j++) {
            let value="";
            let item = gridReturn[j];
            //字段类型 单值 双值 多值
            let valMode = item.valMode;
            let bindField = item.bindField;
            if (!bindField) {
                continue;
            }
            if (valMode == "double") {
                let json = {};
                json.label = data[i][item.returnLabel] || data[i][item.returnLabel.toUpperCase()];
                json.value = data[i][item.returnValue] || data[i][item.returnValue.toUpperCase()];
                value = JSON.stringify(json);
            }else if(valMode=="multi"){
                let newValue={};
                let obj={};
                if (Util.checkJSON(item.returnValue)) {
                    obj=JSON.parse(item.returnValue);
                }else {
                    obj=item.returnValue;
                }
                for(let key in obj){
                    newValue[key]=data[i][obj[key].toUpperCase()]
                }
                value = JSON.stringify(newValue);
            }else {
                value = data[i][item.returnValue] || data[i][item.returnValue.toUpperCase()];
            }
            //目标为主表
            if (gridName == 'curForm') {
                tmpObj[bindField] = (i == 0) ? value : tmpObj[bindField] + "," + value;
            } else {
                let grids = formData[gridName];
                if (Array.isArray(grids) && tableType!="subTable") {
                    if(i === 0 || !subObj[bindField]){
                        subObj[bindField] = value
                    }else {
                        subObj[bindField] =  subObj[bindField] + "," + value;
                    }
                    isSubData=true;
                } else {
                    tmpObj[bindField] = value;
                }
            }
        }
        //添加子表行
        if(isSubData){
            subAry.push(subObj);
        }
    }
    if (gridName) {
        //对主表插入数据
        if (gridName == 'curForm') {
            for (let key in tmpObj) {
                formData[key]=tmpObj[key];
            }
        } else { //对子表插入数据
            let grids =formData[gridName];
            if (Array.isArray(grids)) {//数组则目标为一对多子表
                if(tableType=="subTable"){//当前为一对多时
                    for (let key in tmpObj) {
                        row[key]=tmpObj[key];
                    }
                    return;
                }
                if (!subAry || subAry.length == 0) return;
                //追加
                if (config.superaddition) {
                    let uniqueField = config.uniqueField;
                    for (let i = 0; i < subAry.length; i++) {
                        let canAdd = CustomQuery.canAddRow(uniqueField, subAry[i], grids);
                        if (canAdd) {
                            grids = grids.concat([subAry[i]]);
                        }
                    }
                }else {
                    grids = subAry;
                }
                formData[gridName]=grids;
            } else {//一对一子表
                for (let key in tmpObj) {
                    grids[key] = tmpObj[key];
                }
                formData[gridName]=grids;
            }
        }
    }
}
/**
 * <pre>
 * 判断是否添加
 * </pre>
 * @param uniqueField
 * @param newRow
 * @param subTableData
 * @returns {boolean}
 */
CustomQuery.canAddRow = function (uniqueField, newRow, subTableData) {
    if (!uniqueField) {
        return true;
    }
    let val = newRow[uniqueField];
    let ary = subTableData.filter(item => {
        return item[uniqueField] == val;
    });
    if (ary.length == 0) {
        return true;
    }
    return false;
}

export default CustomQuery;
